import React from 'react';
import { Button, Divider, Table, Space, message, Radio, Modal } from 'antd';
import './App.css';
import axios from 'axios'
import Todo from './Todo'
import moment from 'moment'

// const requestUrl = 'http://127.0.0.1/api'

class App extends React.Component {
  constructor(prop) {
    super(prop)
    this.state = {
      drawerTitle: '新增任务',
      visible: false,
      todoList: [],
      formData: {},
      filterValue: '', // 选择筛选的值
      // filteredInfo: null, // 筛选
      sortedInfo: null, // 排序
    }
  }

  // 组件第一次渲染完成
  componentDidMount() {
    this.getDataList('0')
  }
  
  // 获取数据列表 '0' 查看全部
  getDataList = (status) => {
    const that = this
    axios.post(`/todoapi/list`, {
      status: status
    })
    .then(function (response) {
      console.log(response.data.list.rows);
      const dataList = response.data.list.rows
      let todoList = []
      for (let item of dataList) {
        let deadline = new Date(item.deadline)
        
        todoList.push({
          key: item.id,
          name: item.name,
          status: item.status,
          deadline:moment(deadline).format("YYYY-MM-DD HH:mm:ss"),
          content: item.content
        })
      }
      that.setState({
        todoList
      })
      console.log(that.state.todoList);
    })
    .catch(function (error) {
      console.log(error);
    });
  }
  formRef = React.createRef();
  // 显示任务抽屉--新增任务
  showDrawer = () => {
    this.setState({
      visible: true,
      formData: {}
    }, ()=>{
      console.log('新增任务', this.state.visible)
    })
  }
  // 关闭任务抽屉
  onClose = (type) => {
    if (type === 1) {
      this.getDataList('0')
    }
    this.setState({
      visible: false
    })
  }
  // 重置内容
  // onReset = () => {
  //   this.formRef.current.resetFields();
  // };
  // 选择截止日期
  // onChange = (date, dateString) => {
  //   console.log(date, dateString)
  //   console.log(this.state.formData)
  // }
  // 提交表单
  // handleSubmit = (values) => {
  //   console.log('values', values)
  //   axios.post(`/todoapi/create`, {
  //     data: values
  //   })
  //   .then(function (response) {
  //     console.log(response);
  //     this.setState({
  //       visible: false
  //     })
  //     this.getDataList('0')
  //   })
  //   .catch(function (error) {
  //     console.log(error);
  //   });
  // }
  // 编辑任务
  editHandleClick = (values) => {
    const that = this
    console.log('编辑任务',values)
    that.setState({
      drawerTitle: '编辑任务',
      visible: true,
      formData: values
    },()=>{that.child.editTodo(values, '1')})
    // that.formRef.current.setFieldsValue({
    //   name: values.name,
    //   status: values.status,
    //   deadline: values.deadline,
    //   content: values.content,
    // });
    // console.log(this.state.formData)
  }
  // 删除任务
  deleteTodoItem(id) {
    const that = this
    Modal.confirm({
      title: `确认删除该任务吗？`,
      onOk: () => {
        console.log('删除任务', id)
        axios.get(`/todoapi/delete/${id}`)
        .then(function (response) {
          console.log(response);
          message.success(response.data.message);
          that.getDataList('0')
        })
        .catch(function (error) {
          console.log(error);
        });
      },
      onCancel: () => {
        message.info('已取消删除')
      }
    })
  }

  // 筛选状态
  filterStatus(e) {
    console.log('选择状态', e.target.value);
    this.setState({
      filterValue: e.target.value,
    });
  }
  // 确认筛选
  handleSearch() {
    const filterValue = this.state.filterValue
    console.log('筛选的数据', filterValue)
    this.getDataList(filterValue)
  }

  // 自定义筛选
  getColumnFilterProps = dataIndex => ({
    
    filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
      <div style={{ padding: 8 }}>
        <Radio.Group onChange={this.filterStatus.bind(this)} value={this.state.filterValue}
                     style={{ display: 'flex', flexDirection: 'column' }}>
          <Radio value={'0'}>
            全部
          </Radio>
          <Radio value={'1'}>
            待办
          </Radio>
          <Radio value={'2'}>
            正在进行
          </Radio>
          <Radio value={'3'}>
            已完成
          </Radio>
        </Radio.Group>
        <Space>
          <Button
            type="primary"
            onClick={() => this.handleSearch(selectedKeys, confirm, dataIndex)}
            size="small"
            style={{ width: 90 }}
          >
            确认
          </Button>
        </Space>
      </div>
    ),
    onFilter: (value, record) =>
      record[dataIndex]
        ? record[dataIndex].toString().toLowerCase().includes(value.toLowerCase())
        : '',
  });

  // 筛选和排序表格
  handleChange = (pagination, filters, sorter) => {
    console.log('表格变化', pagination, filters, sorter);
    this.setState({
      // filteredInfo: filters,
      sortedInfo: sorter,
    });
  };

  // clearFilters = () => {
  //   this.setState({ filteredInfo: null });
  // };

  // clearAll = () => {
  //   this.setState({
  //     filteredInfo: null,
  //     sortedInfo: null,
  //   });
  // };

  render() {
    let { sortedInfo, filteredInfo } = this.state;
    sortedInfo = sortedInfo || {};
    // filteredInfo = filteredInfo || {};
    const columns = [
      {
        title: 'ID',
        dataIndex: 'key',
        key: 'key',
        sorter: (a, b) => a.key - b.key,
        sortOrder: sortedInfo.columnKey === 'key' && sortedInfo.order,
        ellipsis: true,
      },
      {
        title: '任务名称',
        dataIndex: 'name',
        key: 'name',
        // sorter: (a, b) => a.name.length - b.name.length,
        // sortOrder: sortedInfo.columnKey === 'name' && sortedInfo.order,
        ellipsis: true,
      },
      {
        title: '任务内容',
        dataIndex: 'content',
        key: 'content',
        // sorter: (a, b) => a.content - b.content,
        // sortOrder: sortedInfo.columnKey === 'content' && sortedInfo.order,
        ellipsis: true,
      },
      {
        title: '截止日期',
        dataIndex: 'deadline',
        key: 'deadline',
        // sorter: (a, b) => a.deadline - b.deadline,
        // sortOrder: sortedInfo.columnKey === 'deadline' && sortedInfo.order,
        ellipsis: true,
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'stauts',
        filters: [
          { text: '待办', value: '1' },
          { text: '正在进行', value: '2' },
          { text: '完成', value: '3' },
          { text: '全部', value: '0' },
        ],
        // filterMultiple: true, // 是否多选
        // filteredValue: filteredInfo.stauts || null,
        // onFilter: (value, record) => record.stauts == value,
        ...this.getColumnFilterProps('stauts'),
        ellipsis: true,
        render: (text, record) => {
          if (text === '1') {
            return (
              <Space size="middle">
                <div>待办</div>
              </Space>
            )
          } else if (text === '2') {
            return (
              <Space size="middle">
                <div>正在进行</div>
              </Space>
            )
          } else {
            return (
              <Space size="middle">
                <div>完成</div>
              </Space>
            )
          }
        },
      },
      {
        title: '操作',
        key: 'action',
        render: (text, record) => (
          <Space size="middle">
            <a onClick={() => this.editHandleClick(record)}>编辑</a>
            <a onClick={() => this.deleteTodoItem(record.key)}>删除</a>
          </Space>
        ),
      },
    ];
    return (
      <div className="App">
        <Divider plain className="titleDivider">任务列表</Divider>
        <Button size='large' onClick={this.showDrawer}>新增</Button>
        <Todo openTodo={this.state.visible}
              drawerTitle={this.state.drawerTitle}
              // formData={this.state.formData}
              closeTodo={this.onClose.bind(this)}
              onRef={(ref)=>{ this.child = ref}}
        ></Todo>
        <Table style={{marginTop: 20}} columns={columns} dataSource={this.state.todoList} onChange={this.handleChange} />
      </div>
    );
  }
}

export default App;
